﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using P2PLib.Common.DataModel;
using System.Net;

namespace P2PLib.Common.Command
{
    public class CSNewClientCommand:CSCommandBase
    {
        private ClientInfo client;
        public ClientInfo Client {
            set {
                this.client = value;
            }
            get {
                return this.client;
            }
        }

        public CSNewClientCommand()
            : base(CSCommandType.NewClient)
        {
            this.client = new ClientInfo("127.0.0.1", 1234);
        }

        public CSNewClientCommand(ClientInfo ci)
            : base(CSCommandType.NewClient)
        {
            this.client = ci;
        }

        public override void ReadFromStream(System.IO.Stream stream)
        {
            byte[] buffer = new byte[4];
            stream.Read(buffer, 0, 4);
            this.client.Port = BitConverter.ToInt32(buffer, 0);
            stream.Read(buffer, 0, 4);
            int ipSize = BitConverter.ToInt32(buffer, 0);
            buffer = new byte[ipSize];
            stream.Read(buffer, 0, ipSize);
            this.client.IP = IPAddress.Parse(Encoding.ASCII.GetString(buffer));
        }
        public override void WriteToStream(System.IO.Stream stream)
        {
            byte[] buffer = BitConverter.GetBytes(this.client.Port);
            stream.Write(buffer, 0, 4);
            //write the client's ip size to the stream
            buffer = Encoding.ASCII.GetBytes(this.client.IP.ToString());
            stream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);
            //write the client's ip to the stream
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}
